import { defineStore } from "pinia";
import { clearAllRegisteredRouter } from "@/utils/registerRouter";
import { SessionStorage } from "@/utils/storage";
import { openNewWindowMap } from "@/utils/window";
const getPermissions = (treeData: any[], permissions: any[]) => {
  treeData.forEach((item) => {
    const { slug, is_menu, visible } = item;
    if (+is_menu === 2 && !!visible && slug.indexOf("POST:") === 0)
      permissions.push(slug);
    item?.children?.length ? getPermissions(item.children, permissions) : [];
  });
};
const deepTreeData: any = (treeData: any[]) => {
  return treeData.map((item) => {
    const { slug, http_path, name, is_menu, visible, icon } = item;
    return {
      path: http_path,
      name: slug,
      meta: {
        keepAlive: true,
        visible: !!visible,
        title: name,
        icon: icon,
        page_type: is_menu,
        isOpenNewWindow: !!openNewWindowMap[http_path],
      },
      children:
        is_menu === 0 && item?.children?.length
          ? deepTreeData(item.children)
          : [],
    };
  });
};
export const useRouteStore = defineStore("routes", {
  state: () => ({ routes: [] as any[], powers: [] as any[], im_routes: [] }),
  getters: {
    getRoutes: (state) => state.routes,
  },
  actions: {
    set_im_routes(value) {
      this.im_routes = value;
    },
    setRoutes(routes: any) {
      this.routes = routes;
    },
    setPowers(powers: any) {
      this.powers = powers;
    },
    async fetchMenuList() {
      try {
        /*const result: any = await import("@/routes/async.router"); // 模拟获取菜单栏数据
      this.setRoutes(result.asyncRoutes);*/
        clearAllRegisteredRouter();
        const result: any = await menuApi.querySiderTree();
        if (result.code !== 200) return message.error(result.message);
        this.set_im_routes(result.data);
        const routes = deepTreeData(result.data);
        const permissions = reactive<any[]>([]);
        getPermissions(result.data, permissions);
        this.setPowers(permissions);
        this.setRoutes(routes);
        return result;
      } catch (error: any) {
        message.error(error.message);
      } finally {
      }
    },
  },
  persist: {
    enabled: true,
    strategies: [
      { storage: SessionStorage, paths: ["routes", "powers", "im_routes"] },
    ],
  },
});
